<?php 
class App{
	private static $instance;
	private $app;
	public static function import($path)
	{
		set_include_path(get_include_path().PATH_SEPARATOR . $path);
	}

	public static function getInstance($configure)
	{
		if(empty(self::$instance)) {
			self::$instance =new self($configure);
		}
		return self::$instance;
	}

	public function loadImport($patharr)
	{
		foreach($patharr as $item) {
			$arr = explode('.', $item);
			$path = '';
			foreach($arr as &$items) {
				$items = $this->getAlias($items);
			}
			if($items == '*') { //如果为通配符，则递归加载
				array_pop($arr);
			    $path = implode('\\', $arr);
			    self::import($path);
				$this->loadPath($path);
			}
		}
	}

	public function terminate()
	{
		exit;
	}
	
	public function loadAClasslias($classmap)
	{
		foreach($classmap as $key=>$item) 
		{
			class_alias($item,$key);
		}
	}

	public function getAlias($name)
	{
		return  isset($this->app[$name])?$this->app[$name]:$name;
	}


	public function loadPath($path)
	{
		$filearr = scandir($path);
		foreach($filearr as $dir) {
			if(($dir=='.')||($dir=='..')) {
				continue;
			}
			if(is_dir($path.'\\'.$dir)) {
				self::import($path.'\\'.$dir);
				$this->loadPath($path.'\\'.$dir);
			}
		}
	}

	public function getBasePath()
	{
		return $this->app['xphp'];
	}	

	public function setBasePath($path)
	{
		$this->app['xphp'] = $path;
	}

	public function __construct($configure)
	{
		$this->setBasePath($configure['basePath']);
		$root = $this->getBasePath();
		$this->loadImport($configure['import']);
		Config::loadArray($configure);
		$this->loadAClasslias($configure['classmap']);
		self::import($root);
		self::import($root."\\controller\\");
		self::import($root."\\model\\");
	}
	public static function run()
	{
		$c = isset($_GET['c'])?$_GET['c']:'site';
		$action = isset($_GET['a'])?$_GET['a']:'index';
		$c = ucfirst($c).'Controller'; 
		$action = 'Action'.ucfirst($action);

		$controller = new $c();
		
		if(method_exists($controller,'beforeAction')) {
			$controller->beforeAction();
		}

		$controller->$action();
		
		if(method_exists($controller,'afterAction')) {
			$controller->afterAction();	
		}
	}

	public static function  classAutoLoader($class)
	{
		$file = $class.'.php';
   		include $file;
	}
}